<template>
  <div class="divide-policy">
    <Card class="userCard">
      <Form :model="form">
        <Row gutter="30">
          <i-col span="6">
            <FormItem>
              <Cascader change-on-select :data="reagentOrganizationList" v-model="form.manageCom" @on-change="organizationChange" placeholder="管理机构" clearable></Cascader>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem>
              <Select v-model="form.saleChnl" placeholder="渠道" clearable>
                <Option
                  :value="item.saleChnl"
                  v-for="item in salechnlList"
                  :key="item.saleChnl"
                  >{{ item.saleChnlName }}</Option
                >
              </Select>
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="50">
          <i-col span="8">
            <FormItem>
              <Button
                type="primary"
                @click="queryPolicy(1)"
                :loading="queryLoading"
                style="margin-right: 20px"
                >查询</Button
              >
              <Button type="primary" @click="addPolicy">新增</Button>
            </FormItem>
          </i-col>
        </Row>
      </Form>
      <!-- </Row> -->
      <!-- 表格 -->
      <Table :columns="columns1" :data="data1">
        <template slot-scope="{ row }" slot="comName">
          {{ row.manageCom }}-{{ row.manageComName }}
        </template>
        <template slot-scope="{ row }" slot="agentGroup1Name">
          {{ row.agentGroup1 }}-{{ row.agentGroup1Name }}
        </template>
        <template slot-scope="{ row }" slot="agentGroup2Name">
          {{ row.agentGroup2 }}-{{ row.agentGroup2Name }}
        </template>
        <template slot-scope="{ row }" slot="reAgentCode">
          {{ row.reAgentCode }}-{{ row.reAgentName }}
        </template>

        <template slot-scope="{ row }" slot="reAgentGroup1Name">
          {{ row.reAgentGroup1 }}-{{ row.reAgentGroup1Name }}
        </template>
        <template slot-scope="{ row }" slot="reAgentGroup2Name">
          {{ row.reAgentGroup2 }}-{{ row.reAgentGroup2Name }}
        </template>
        <template slot-scope="{ row }" slot="operate">
          <Button type="primary" @click="editPolicy(row)">修改</Button>
        </template>
      </Table>

      <!-- 分页 -->
      <Row>
        <i-col span="24" style="text-align: right; margin-top: 20px">
          <Page
            :total="total"
            show-total
            show-sizer
            @on-change="pageChange"
            @on-page-size-change="pageSizeChange"
            :page-size-opts="pageSizeOptions"
            :current="pageIndex"
            :page-size="pageSize"
          />
        </i-col>
      </Row>
      <Button type="primary" @click="info" v-if="false"></Button>
    </Card>
  </div>
</template>
<script>
import Cookies from "js-cookie";
export default {
  data() {
    const validateMonth = (rule, value, callback) => {
      let regstr = /^(?:1[0-2]|[1-9])$/;
      if (regstr.test(value)) {
        callback();
      } else {
        callback(new Error("请输入1-12的整数"));
      }
      callback();
    };
    return {
      salechnlList: [],
      saveGroup1: "",
      saveGroup2: "",
      savereName: "",
      modalFlag: "",
      // 当前页码
      pageIndex: 1,
      // 每页记录数量
      pageSize: 10,
      //  每页条数切换的配置
      pageSizeOptions: [5, 10, 15, 20],
      //  总数量
      total: 0,
      pageObj: null,
      form: {
        manageCom: "",
        saleChnl: "",
      },
      addForm: {
        branchType: "1",
        manageCom: "",
        batchType: "",
        reAgentCode: "",
        agentGroup1: "",
        agentGroup2: "",
        agentMonth: 3,
      },
      ruleValidate: {
        branchType: [{ required: true, message: "请选择", trigger: "blur" }],
        manageCom: [{ required: true, message: "请选择", trigger: "blur" }],
        batchType: [{ required: true, message: "请选择", trigger: "blur" }],
        reAgentCode: [{ required: true, message: "请选择", trigger: "blur" }],
        // agentGroup1: [
        //     { required: true, message: '请选择', trigger: 'blur' }
        // ],
        agentGroup2: [{ required: true, message: "请选择", trigger: "blur" }],
        agentMonth: [
          { validator: validateMonth, trigger: "change" },
          // { type: 'number', message: '请输入', trigger: 'change' }
        ],
      },
      //   stateList: [
      //     { key: '0', value: '活跃' },
      //     { key: '1', value: '不活跃' },
      //     { key: '2', value: '全部' }
      //   ],

      // 表格数据
      columns1: [
        {
          title: "管理机构",
          slot: "comName",
          //   slot: 'indexNo',
          width:'450',
          align: "center",
        },
        {
          title: "渠道",
          key: "saleChnlName",
          align: "center",
        },
        {
          title: "问卷创建时间",
          key: "createTime",
          align: "center",
        },
        {
          title: "创建人",
          key: "creator",
          align: "center",
        },
        {
          title: "上次修改时间",
          key: "updateTime",
          align: "center",
        },
        {
          title: "修改人",
          key: "operator",
          align: "center",
        },
        {
          title: "操作",
          slot: "operate",
          align: "center",
          fixed: "right",
        },
      ],
      data1: [],
      queryLoading: false,
      openModal: false,
      saleChannelList: [],
      reagentOrganizationList: [],
      reagentNameList: [],
      reagentNameListAdd: [],
      agentGroup1List: [],
      agentGroup1ListAdd: [],
      agentGroup2List: [],
      agentGroup2ListAdd: [],
      submitLoading: false,
    };
  },
  methods: {
    info(tip) {
      this.$Message.warning(tip);
    },
    //
    queryPolicy(flag) {
      if (flag) {
        this.pageIndex = flag;
      }
      this.queryLoading = true;
      let obj = {
        saleChnl: this.form.saleChnl || null,
        manageCom: this.form.manageCom[this.form.manageCom.length-1] || null,
      };
      obj.index = this.pageIndex;
      obj.pageSize = this.pageSize;
      this.api
        .getByConditionsurvey(obj)
        .then((res) => {
          if (res.code == 200 && res.data) {
            this.queryLoading = false;
            this.data1 = res.data.records;
            this.total = res.data.total;
          } else {
            this.data1 = [];
            this.queryLoading = false;
          }
        })
        .catch((e) => {
          this.data1 = [];
          this.queryLoading = false;
          this.$Message.error("请求异常");
        });
    },

    pageChange(e) {
      this.pageIndex = e;
      this.queryPolicy();
    },
    pageSizeChange(e) {
      this.pageSize = e;
      this.queryPolicy();
    },
    cancel() {
      //弹窗数据初始化
      this.openModal = false;
    },
    addPolicy() {
      this.$router.push({
        name: "addQuestionnaire",
      });
    },
    editPolicy(row) {
      let arr = []
      this.reagentOrganizationList.forEach(one=>{
        if (one.value == row.manageCom) {
          arr.push(one.value)
        }else if(one.children){
          one.children.forEach(two=>{
            if (two.value == row.manageCom) {
              arr.push(one.value,two.value)
            }else if (two.children) {
              two.children.forEach(three=>{
                if (three.value == row.manageCom) {
                  arr.push(one.value,two.value,three.value)
                }else if(three.children){
                  three.children.forEach(four=>{
                    if (four.value == row.manageCom) {
                      arr.push(one.value,two.value,three.value,four.value)
                    }
                  })
                }
              })
            }
          })
        }
      })
      console.log(arr,'arr');
      row.manageCom = arr
      this.$router.push({
        name: "addQuestionnaire",
        query: {
          row,
        },
      });
    },
    modalVisibleChange(flag) {
      if (flag) {
      } else {
        this.$refs["addForm"].resetFields();
      }
    },
    // 进入页面初始化
    initialize() {
      this.api.remanagecomList().then(res => {
        if (res.code == 200 && res.data != null) {
          let arr = []
          arr.push(res.data)
          arr.forEach(one=>{
            one.value = one.comcode
            one.label = one.comcode + '-' + one.name
            one.children = one.chilDren || []
            if (one.children) {
              one.chilDren.forEach(two=>{
                two.value = two.comcode
                two.label = two.comcode + '-' + two.name
                two.children = two.chilDren || []
                if (two.children) {
                  two.children.forEach(three=>{
                    three.value = three.comcode
                    three.label = three.comcode + '-' + three.name
                    three.children = three.chilDren || []
                    if (three.children) {
                      three.children.forEach(four=>{
                        four.value = four.comcode
                        four.label = four.comcode + '-' + four.name
                        four.children = four.chilDren || []
                      })
                    }
                  })
                }
              })
            }
          })
          console.log(arr);
          this.reagentOrganizationList = arr
        } else {
          this.reagentOrganizationList = [];
        }
      });
      this.api.professionalList().then((res) => {
        if (res.code == 200 && res.data != null) {
          if (res.data.salechnlListVOS) {
            let list = res.data.salechnlListVOS;
            list.map((item) => {
              item.key = Number(item.key).toString();
            });
            this.saleChannelList = list;
          }
          // if (res.data.listKeyValueVOS) {
          //   this.reagentOrganizationList = res.data.listKeyValueVOS;
          //   sessionStorage.setItem(
          //     "reagentOrganizationList",
          //     JSON.stringify(this.reagentOrganizationList)
          //   );
          // }
          //   if (res.data.payintvVOS) {
          //     this.payList = res.data.payintvVOS;
          //   }
          //   if (res.data.contstateListVOS) {
          //     this.applyStatusList = res.data.contstateListVOS;
          //   }
        } else {
          // this.reagentorganizationList = [];
          this.saleChannelList = [];
          this.workStatusList = [];
          this.payList = [];
          this.applyStatusList = [];
        }
      });
    },
    // 根据管理机构查询续期专员
    organizationChange(value) {
      if (!value) {
        if (!this.openModal) {
          this.reagentNameList = [];
        } else {
          this.reagentNameListAdd = [];
        }
      } else {
        $.ajax("scrm-gateway/scrm-uer/api/List/sekectreangencode/" + value[value.length-1], {
          method: "get",
          contentType: "application/json;charset=utf-8",
          headers: {
            Authorization: sessionStorage.getItem("credentials"),
          },
          success: (res) => {
            if (res.code == 200 && res.data != null) {
              //   this.reagentNameList = res.data;
              if (!this.openModal) {
                this.reagentNameList = res.data;
              } else {
                this.reagentNameListAdd = res.data;
                if (this.savereName) {
                  this.addForm.reAgentCode = this.savereName;
                  this.savereName = "";
                }
              }
            } else {
              if (!this.openModal) {
                this.reagentNameList = [];
              } else {
                this.reagentNameListAdd = [];
              }
            }
          },
          error: (res) => {
            this.$Message.error(res.msg);
          },
        });
        this.api
          .queryPartGroups({
            codeType: "1",
            code: value[value.length-1],
          })
          .then((res) => {
            if (res) {
              if (!this.openModal) {
                this.agentGroup1List = res;
              } else {
                this.agentGroup1ListAdd = res;
                if (this.saveGroup1) {
                  this.addForm.agentGroup1 = this.saveGroup1;
                  this.saveGroup1 = "";
                  this.queryGroup(this.addForm.agentGroup1);
                }
              }
            } else {
              if (!this.openModal) {
                this.agentGroup1List = [];
              } else {
                this.agentGroup1ListAdd = [];
              }
            }
          });
      }
    },
    //查询组
    queryGroup(value) {
      this.api
        .queryPartGroups({
          codeType: "2",
          code: value,
        })
        .then((res) => {
          if (res) {
            if (!this.openModal) {
              this.agentGroup2List = res;
            } else {
              this.agentGroup2ListAdd = res;
              if (this.saveGroup2) {
                this.addForm.agentGroup2 = this.saveGroup2;
                this.saveGroup2 = "";
              }
            }
          } else {
            if (!this.openModal) {
              this.agentGroup2List = [];
            } else {
              this.agentGroup2ListAdd = [];
            }
          }
        });
    },
    reset() {
      this.form = {
        branchType: "",
        manageCom: "",
        batchType: "",
        reAgentCode: "",
        agentGroup1: "",
        agentGroup2: "",
      };
      this.reagentNameList = [];
    },

    // 修改信息确认
    resetPswSubmit() {
      this.$refs.resetPswForm.validate((valid) => {
        if (valid) {
        }
      });
    },
    saveUpdate() {
      this.api.resetPwd(this.updateObj).then((res) => {
        if (res.code == 200) {
        } else {
          this.$Message.info("工号已存在");
        }
      });
    },
    getSaleChnl() {
      this.api.getSaleChnl().then((res) => {
        this.salechnlList = res.data;
      });
    },
  },
  mounted() {
    // 进入页面初始化
    this.initialize();
    // this.organizationChange();
    // this.organizationChange(this.form.reagentOrganization);
    this.queryPolicy();
    this.getSaleChnl();
  },
};
</script>
<style lang="less">
.ivu-modal-header {
  background-color: #2d8cf0 !important;
}
.divide-policy {
  .ivu-input-number {
    width: 100% !important;
  }
}

.divide-policy .ivu-input-number {
  width: 100%;
}
</style>

<style scoped lang="less">
@import "./user";
.ivu-modal-header {
  background-color: #2d8cf0;
}
.ivu-modal-close .ivu-icon-ios-close {
  color: #fff;
}

.stopClass > .ivu-modal {
  top: 0;
  left: 25px;
}
.addClass > .ivu-modal {
  top: 140px;
}
.updateClass > .ivu-modal {
  top: 140px;
}
.btngroup {
  width: 100%;
  display: flex;
  justify-content: center;
}
.btngroup .ivu-col-span-8 {
  display: inline-block;
  width: 100px;
}
</style>

